import 'package:flutter/material.dart';
import '../models/word.dart';
import '../services/database_service.dart';

class QuizScreen extends StatefulWidget {
  @override
  _QuizScreenState createState() => _QuizScreenState();
}

class _QuizScreenState extends State<QuizScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<Word> _words = [];
  int _currentIndex = 0;
  bool _showAnswer = false;
  bool _isCorrect = false;

  @override
  void initState() {
    super.initState();
    _loadWords();
  }

  Future<void> _loadWords() async {
    _words = await _databaseService.getWords();
    setState(() {});
  }

  void _checkAnswer(bool answer) {
    setState(() {
      _isCorrect = answer;
      _showAnswer = true;
    });
  }

  void _nextQuestion() {
    setState(() {
      _currentIndex++;
      _showAnswer = false;
      _isCorrect = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_words.isEmpty) {
      return Scaffold(
        appBar: AppBar(title: Text('单词测试')), 
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (_currentIndex >= _words.length) {
      return Scaffold(
        appBar: AppBar(title: Text('单词测试')), 
        body: Center(child: Text('测试完成！')), 
      );
    }

    final currentWord = _words[_currentIndex];

    return Scaffold(
      appBar: AppBar(title: Text('单词测试')), 
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '单词: ${currentWord.word}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            if (_showAnswer)
              Text(
                _isCorrect ? '正确！' : '错误！',
                style: TextStyle(fontSize: 24, color: _isCorrect ? Colors.green : Colors.red),
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _checkAnswer(true),
              child: Text('这是正确的意思'),
            ),
            ElevatedButton(
              onPressed: () => _checkAnswer(false),
              child: Text('这是错误的意思'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _nextQuestion,
              child: Text('下一题'),
            ),
          ],
        ),
      ),
    );
  }
}
